package com.osfw.dbadminer.controller.database;

import com.osfw.framework.annotation.Log;
import com.osfw.framework.exception.ServiceException;
import com.osfw.framework.enums.BusinessType;
import com.osfw.dbadminer.service.connect.IDbaConnectDatabaseService;
import com.osfw.dbadminer.service.database.IDbaDataBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 数据库操作
 */
@Controller
@RequestMapping("/osfw/dbadminer/database")
public class DbaDatabaseController {
    private String prefix = "osfw/dbadminer/database";

    @Autowired
    private IDbaConnectDatabaseService connectDatabaseService;
    @Autowired
    private IDbaDataBaseService dataBaseService;


    @Log(title = "查询数据库", businessType = BusinessType.GRANT)
    @GetMapping("/list/{connectId}")
    @ResponseBody
    public List<String> list(@PathVariable("connectId") Long connectId) {
        try {
            List<String> filterDatabases = connectDatabaseService.getFilterDbByConnectId(connectId);
            List<String> allDatabases = dataBaseService.getAllDatabases(connectId);
            allDatabases = allDatabases.stream()
                    .filter(x -> filterDatabases.isEmpty() || filterDatabases.contains(x))
                    .collect(Collectors.toList());
            return allDatabases;
        } catch (SQLException e) {
            ServiceException.throw500(e.getMessage());
        }
        return new ArrayList<>();
    }

}
